package com.yhp.web;

import com.yhp.bean.Users;
import com.yhp.service.UsersService;
import com.yhp.service.impl.UsersServiceImpl;
import com.yhp.util.PageUtil;
import com.yhp.util.PageUtilPlus;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = "/usersServlet")
public class UsersServlet extends HttpServlet {
    protected void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数+设置编码
        //req.setCharacterEncoding("utf-8");
        String uname = req.getParameter("uname");
        String usex = req.getParameter("usex");
        String uage = req.getParameter("uage");
        String upass = req.getParameter("upass");
        //2.调取方法
        UsersService usersService=new UsersServiceImpl();
        Users users = new Users();
        users.setUserName(uname);
        users.setSex(usex);
        users.setAge(Integer.parseInt(uage));
        users.setPassWord(upass);
        int i = usersService.insert(users);
        //3.返结果
        //resp.setContentType("text/html;charset=utf-8"); Myfilter1已经设置编码方式
        PrintWriter writer = resp.getWriter();
        if(i>0){
            //writer.print("<script type='text/javascript'>alert('新增成功');location.href='/usersServlet?key=selectusers&pageindex=1'</script>");
            writer.print("<script type='text/javascript'>alert('新增成功');location.href='/index.jsp'</script>");
        }else{
            writer.print("<script type='text/javascript'>alert('新增失败');location.href='/add.jsp'</script>");
        }
    }

    protected void deleteByID(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数
        String userid=(String) req.getParameter("userid");
        int uid=Integer.parseInt(userid);

        //2.调取逻辑
        UsersService usersService=new UsersServiceImpl();
        int i = usersService.deleteById(uid);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if(i>0){
            //删除成功
            // deleteservlet->location.href->selectusersservlet->list.jsp
            writer.print("<script type='text/javascript'>alert('删除成功');location.href='/usersServlet?key=selectusers&pageindex=1'</script>");
        }else{
            //删除失败
            writer.print("<script type='text/javascript'>alert('删除失败');location.href='/usersServlet?key=selectusers&pageindex=1'</script>");
        }
    }

    protected void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接参数
        String userid = req.getParameter("userid");
        //2.调逻辑
        UsersService usersService=new UsersServiceImpl();
        int i = usersService.deleteUser(Integer.parseInt(userid));
        //3.返结果
        //resp.setContentType("text/html;charset=utf-8"); Myfilter1已经设置编码方式
        PrintWriter writer = resp.getWriter();
        if(i>0){
            //删除成功
            // deleteservlet->location.href->selectusersservlet->list.jsp
            writer.print("<script type='text/javascript'>alert('删除成功');location.href='/usersServlet?key=selectusers&pageindex=1'</script>");
        }else{
            //删除失败
            writer.print("<script type='text/javascript'>alert('删除失败');location.href='/usersServlet?key=selectusers&pageindex=1'</script>");
        }
    }

    protected void loginOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //清除session,跳转页面
        HttpSession session = req.getSession();
        session.invalidate();
        //跳转index.jsp页面
        resp.sendRedirect("index.jsp");
    }

    protected void login(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        //1.接参数(记得处理编码方式)
        request.setCharacterEncoding("utf-8"); //Myfilter1已经设置编码方式
        String username = request.getParameter("username");//要和表单中的name值相同
        String userpass = request.getParameter("userpass");
        //2.写逻辑（面向接口编程）
        UsersService usersService=new UsersServiceImpl();
        Users u = usersService.login(username, userpass);
        //3.返结果
        //resp.setContentType("text/html;charset=utf-8"); //Myfilter1已经设置编码方式
        PrintWriter writer = resp.getWriter();
        if(u==null){
            //登录失败(在后端返回给前端一个js弹窗)-如果使用js，则不要再使用重定向或转发的形式跳页面
            //location.href 属于重定向跳转页面
            writer.print("<script type='text/javascript'>alert('用户名或密码不正确');location.href='index.jsp'</script>");
        }else{
            //登录成功
            HttpSession session = request.getSession();
            session.setAttribute("u1",u);
            writer.print("<script type='text/javascript'>alert('登录成功');location.href='success.jsp'</script>");
        }
    }

    protected void selectByID(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接参数
        String userid=req.getParameter("userid");
        //2.调方法
        UsersService service=new UsersServiceImpl();
        Users users = service.selectByid(Integer.parseInt(userid));
        //3.返结果
        req.setAttribute("user",users);
        req.getRequestDispatcher("update.jsp").forward(req,resp);
    }

    protected void selectAllUsers(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接参数
        //req.setCharacterEncoding("utf-8"); Myfilter1已经设置编码方式
        String pageindex = req.getParameter("pageindex");
        //如果没有接收到pageindex，默认查询第一页
        int index = pageindex==null?1:Integer.parseInt(pageindex);//页码值
        //接收模糊查条件,记得设置编码方式
        String uname= req.getParameter("uname"); //第一次进来：null  第二次进来时：""
        String usex = req.getParameter("usex");//第一次进来：null    第二次进来时：""
        //2.调逻辑
        UsersService usersService=new UsersServiceImpl();
        List<Users> users = usersService.selectAll(index, PageUtil.PAGESIZE,uname,usex);
        // 每页展示数据时，不够一页，也会单独占一页的位置
        //总页数=总条数%每页显示条数>0?总条数/每页显示条数+1:总条数/每页显示条数
        int total = usersService.totalCount(uname,usex); //总条数
        //  int totalPages=total%PageUtil.PAGESIZE>0?total/PageUtil.PAGESIZE+1:total/PageUtil.PAGESIZE;//总页数
        //3.返结果(后端给前端传数据，必然设计到存值问题)
      /*  req.setAttribute("ulist",users);
        req.setAttribute("pindex",index);
        req.setAttribute("totalcount",total);
        req.setAttribute("totalpages",totalPages);*/
        PageUtilPlus<Users> usersPageUtilPlus = new PageUtilPlus<>();
        usersPageUtilPlus.setPageIndex(index);
        usersPageUtilPlus.setTotalCount(total);
        // usersPageUtilPlus.setTotalPages(totalPages);
        usersPageUtilPlus.setDataList(users);
        req.setAttribute("pu",usersPageUtilPlus);
        //存储模糊查条件
        req.setAttribute("username",uname);
        req.setAttribute("usersex",usex);
        req.getRequestDispatcher("/list.jsp").forward(req,resp);
    }
    protected void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接受参数+处理post请求的乱码
        //req.setCharacterEncoding("utf-8");  Myfilter1已经设置编码方式
        String uid = req.getParameter("uid");
        String uname = req.getParameter("uname");
        String usex = req.getParameter("usex");
        String uage = req.getParameter("uage");
        String upass = req.getParameter("upass");
        //2.调取方法
        UsersService usersService=new UsersServiceImpl();
        Users users = new Users();
        users.setUserId(Integer.parseInt(uid));
        users.setUserName(uname);
        users.setSex(usex);
        users.setAge(Integer.parseInt(uage));
        users.setPassWord(upass);
        int i = usersService.updateuser(users);
        //3.返结果
        //resp.setContentType("text/html;charset=utf-8"); Myfilter1已经设置编码方式
        PrintWriter writer = resp.getWriter();
        if(i>0){
            //更新成功，回到展示用户列表的界面（不能直接跳回到list.jsp,而是需要重新发送新的请求，间接走到list.jsp）
            writer.print("<script type='text/javascript'>alert('更新成功');location.href='/usersServlet?key=selectusers&pageindex=1'</script>");
        }else{
            //更新失败,则回到更新页面update.jsp（不能直接跳回到update.jsp,而是需要重新发送新的请求，间接走到update.jsp）
            writer.print("<script type='text/javascript'>alert('更新失败');location.href='/usersServlet?key=selectbyid&userid="+uid+"'</script>");
        }
    }

    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //req.setCharacterEncoding("utf-8"); Myfilter1已经设置编码方式

        String key = req.getParameter("key");
        switch (key){
            case "adduser":
                //新增
                addUser(req,resp);
                break;
            case "deletebyid":
                //假删除
                deleteByID(req,resp);
                break;
            case "deleteuser":
                //真删除
                deleteUser(req,resp);
                break;
            case "loginout":
                //退出
                loginOut(req,resp);
                break;
            case "login":
                //登录
                login(req,resp);
                break;
            case "selectbyid":
                //根据ID查找
                selectByID(req,resp);
                break;
            case "selectusers":
                //查询全部用户
                selectAllUsers(req,resp);
                break;
            case "updateuser":
                //更新用户信息
                updateUser(req,resp);
                break;

        }

    }
}
